package com.xh.rufongwallpaper.controller;

import com.xh.rufongwallpaper.common.constant.Constants;
import com.xh.rufongwallpaper.common.result.Result;
import com.xh.rufongwallpaper.service.WallpaperService;
import com.xh.rufongwallpaper.vo.WallpaperVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 壁纸上传控制器
 */
@RestController
@RequestMapping("/wallpapers")
@RequiredArgsConstructor
@Slf4j
public class WallpaperUploadController {

    private final WallpaperService wallpaperService;

    /**
     * 上传壁纸
     *
     * @param file        壁纸文件
     * @param title       标题
     * @param description 描述
     * @param categoryId  分类ID
     * @param tags        标签（逗号分隔）
     * @return 上传结果
     */
    @PostMapping("/upload")
    public Result<WallpaperVO> uploadWallpaper(MultipartFile file, String title,
                                               String description, Long categoryId, String tags,
                                               @RequestHeader(value = Constants.DEVICE_ID_HEADER, required = false) String deviceId) {

        try {
            log.info("上传壁纸请求: title={}, category={}, deviceId={}, fileSize={}",
                    title, categoryId, deviceId, file.getSize());

            // 参数验证
            if (file.isEmpty()) {
                return Result.failure("请选择要上传的文件");
            }

            if (title == null || title.trim().isEmpty()) {
                return Result.failure("标题不能为空");
            }

            if (categoryId == null) {
                return Result.failure("请选择分类");
            }

            // 调用服务上传
            WallpaperVO wallpaperVO = wallpaperService.uploadWallpaper(file, title, description, categoryId, tags);

            log.info("壁纸上传成功: id={}, title={}", wallpaperVO.getId(), wallpaperVO.getTitle());
            return Result.success(wallpaperVO);
        } catch (IllegalArgumentException e) {
            log.warn("壁纸上传参数错误: {}", e.getMessage());
            return Result.failure(e.getMessage());
        } catch (Exception e) {
            log.error("壁纸上传失败", e);
            return Result.failure("壁纸上传失败: " + e.getMessage());
        }
    }
} 